<template>
  <div class="notification-page">
    <!-- 页面标题和消息统计 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="text-2xl font-bold">消息中心</h2>
        <div class="message-stats">
          <a-space :size="8">
            <span class="total-messages">共 {{ totalMessages }} 条消息</span>
            <a-divider direction="vertical" />
            <span class="unread-messages" v-if="totalUnread > 0">
              <span class="number">{{ totalUnread }}</span> 条未读
            </span>
          </a-space>
        </div>
      </div>
      <div class="header-right">
        <a-space>
          <a-button type="outline" @click="handleMarkAllRead">
            <template #icon><icon-check /></template>
            全部已读
          </a-button>
          <a-button type="outline" status="danger" @click="handleClearAll">
            <template #icon><icon-delete /></template>
            清空消息
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 消息列表区域 -->
    <div class="notification-content">
      <!-- 筛选条件和标签页容器 -->
      <a-card :bordered="false" class="filter-card">
        <!-- 筛选条件 -->
        <div class="filter-section">
          <a-form :model="filterForm" layout="inline">
            <a-form-item field="timeRange" label="时间范围">
              <a-range-picker
                v-model="filterForm.timeRange"
                style="width: 260px"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </a-form-item>
            <a-form-item field="status" label="状态">
              <a-select
                v-model="filterForm.status"
                style="width: 120px"
                placeholder="全部"
                allow-clear
              >
                <a-option value="all">全部</a-option>
                <a-option value="unread">未读</a-option>
                <a-option value="read">已读</a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="module" label="来源模块">
              <a-select
                v-model="filterForm.module"
                style="width: 160px"
                placeholder="全部"
                allow-clear
              >
                <a-option value="all">全部</a-option>
                <a-option value="merchant">商家管理</a-option>
                <a-option value="order">订单管理</a-option>
                <a-option value="content">内容管理</a-option>
                <a-option value="user">用户管理</a-option>
                <a-option value="system">系统</a-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleFilter">
                  <template #icon><icon-search /></template>
                  搜索
                </a-button>
                <a-button @click="resetFilter">
                  <template #icon><icon-refresh /></template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>

        <!-- 标签页和操作按钮 -->
        <div class="tabs-section">
          <div class="tabs-container">
            <a-tabs v-model:activeKey="activeTab" type="text">
              <a-tab-pane key="all" title="全部消息">
                <template #title>
                  <span class="tab-title">
                    全部消息
                    <a-badge
                      :count="totalUnread"
                      :dot="true"
                      v-if="totalUnread > 0"
                    />
                  </span>
                </template>
              </a-tab-pane>
              <a-tab-pane key="pending" title="待处理">
                <template #title>
                  <span class="tab-title">
                    待处理
                    <a-badge
                      :count="pendingUnread"
                      :dot="true"
                      v-if="pendingUnread > 0"
                    />
                  </span>
                </template>
              </a-tab-pane>
              <a-tab-pane key="review" title="待审核">
                <template #title>
                  <span class="tab-title">
                    待审核
                    <a-badge
                      :count="reviewUnread"
                      :dot="true"
                      v-if="reviewUnread > 0"
                    />
                  </span>
                </template>
              </a-tab-pane>
              <a-tab-pane key="alert" title="异常提醒">
                <template #title>
                  <span class="tab-title">
                    异常提醒
                    <a-badge
                      :count="alertUnread"
                      :dot="true"
                      v-if="alertUnread > 0"
                    />
                  </span>
                </template>
              </a-tab-pane>
              <a-tab-pane key="system" title="系统通知">
                <template #title>
                  <span class="tab-title">
                    系统通知
                    <a-badge
                      :count="systemUnread"
                      :dot="true"
                      v-if="systemUnread > 0"
                    />
                  </span>
                </template>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </a-card>

      <!-- 消息列表 -->
      <a-card :bordered="false" class="message-table">
        <a-table
          :loading="loading"
          :data="filteredMessages"
          :pagination="pagination"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
          :bordered="false"
          :stripe="true"
          :hover="true"
          row-key="id"
        >
          <template #columns>
            <!-- 状态列 -->
            <a-table-column title="状态" align="center" width="80">
              <template #cell="{ record }">
                <a-tag :color="record.isRead ? 'gray' : 'blue'" size="small">
                  {{ record.isRead ? "已读" : "未读" }}
                </a-tag>
              </template>
            </a-table-column>

            <!-- 类型列 -->
            <a-table-column title="类型" align="center" width="100">
              <template #cell="{ record }">
                <a-tag
                  :color="getNotificationTypeColor(record.type)"
                  size="small"
                >
                  {{ getNotificationTypeLabel(record.type) }}
                </a-tag>
              </template>
            </a-table-column>

            <!-- 来源模块 -->
            <a-table-column title="来源模块" align="center" width="120">
              <template #cell="{ record }">
                {{ getModuleLabel(record.module) }}
              </template>
            </a-table-column>

            <!-- 标题列 -->
            <a-table-column title="标题" data-index="title">
              <template #cell="{ record }">
                <div class="title-cell">
                  <a-link @click="handleAction(record)">
                    {{ record.title }}
                  </a-link>
                  <span v-if="isNew(record)" class="new-badge">New</span>
                </div>
              </template>
            </a-table-column>

            <!-- 接收时间列 -->
            <a-table-column title="接收时间" align="center" width="180">
              <template #cell="{ record }">
                {{ formatTime(record) }}
              </template>
            </a-table-column>

            <!-- 操作列 -->
            <a-table-column
              title="操作"
              align="center"
              width="280"
              fixed="right"
            >
              <template #cell="{ record }">
                <a-space>
                  <a-button
                    type="text"
                    size="small"
                    @click="handleAction(record)"
                  >
                    查看详情
                  </a-button>
                  <a-divider direction="vertical" />
                  <a-button
                    type="text"
                    size="small"
                    @click="handleMarkRead(record)"
                  >
                    {{ record.isRead ? "标为未读" : "标为已读" }}
                  </a-button>
                  <a-divider direction="vertical" />
                  <a-popconfirm
                    content="确定要删除这条通知吗？"
                    position="left"
                    @ok="handleDelete(record)"
                  >
                    <a-button type="text" status="danger" size="small">
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table-column>
          </template>

          <!-- 空状态 -->
          <template #empty>
            <a-empty description="暂无消息">
              <template #image>
                <icon-inbox
                  style="font-size: 48px; color: var(--color-text-3)"
                />
              </template>
            </a-empty>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconCheck,
  IconDelete,
  IconSearch,
  IconRefresh,
  IconInbox,
} from "@arco-design/web-vue/es/icon";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import { useNotificationStore } from "@/stores/notification";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const notificationStore = useNotificationStore();
const loading = ref(false);
const activeTab = ref("all");

// 分页配置
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 筛选表单
const filterForm = ref({
  timeRange: [],
  status: "all",
  module: "all",
});

// 使用 store 中的消息数据
const messages = computed(() => notificationStore.notifications);

// 计算属性
const totalMessages = computed(() => messages.value.length);
const totalUnread = computed(() => notificationStore.unreadCount.total);
const pendingUnread = computed(() => notificationStore.unreadCount.pending);
const reviewUnread = computed(() => notificationStore.unreadCount.review);
const alertUnread = computed(() => notificationStore.unreadCount.alert);
const systemUnread = computed(() => notificationStore.unreadCount.system);

const filteredMessages = computed(() => {
  let filtered = Array.isArray(messages.value) ? [...messages.value] : [];

  // 添加调试日志
  console.log("计算filteredMessages，原始数据：", filtered.length);
  
  // 如果没有数据，直接返回空数组
  if (filtered.length === 0) {
    return [];
  }

  // 根据标签筛选
  if (activeTab.value !== "all") {
    filtered = filtered.filter((m) => m.type === activeTab.value);
  }

  // 根据状态筛选
  if (filterForm.value.status !== "all") {
    filtered = filtered.filter((m) =>
      filterForm.value.status === "read" ? m.isRead : !m.isRead,
    );
  }

  // 根据模块筛选
  if (filterForm.value.module !== "all") {
    filtered = filtered.filter((m) => m.module === filterForm.value.module);
  }

  // 根据时间范围筛选
  if (filterForm.value.timeRange?.length === 2) {
    const [start, end] = filterForm.value.timeRange;
    filtered = filtered.filter((m) => {
      // 检查是否有createTime字段（API返回的格式）
      const timeField = m.createTime || m.time;
      if (!timeField) {
        console.warn("通知对象缺少时间字段:", m);
        return false;
      }
      const time = dayjs(timeField);
      return time.isAfter(start) && time.isBefore(end);
    });
  }

  // 排序：未读在前，按时间倒序
  filtered.sort((a, b) => {
    if (a.isRead !== b.isRead) return a.isRead ? 1 : -1;
    return new Date(b.time) - new Date(a.time);
  });

  return filtered;
});

// 方法
const formatTime = (timeOrRecord) => {
  // 如果是对象（通知记录）
  if (typeof timeOrRecord === 'object' && timeOrRecord !== null) {
    const record = timeOrRecord;
    // 按优先级尝试不同的时间字段
    const timeField = record.createTime || record.updateTime || record.time || record.readTime;
    if (!timeField) {
      console.warn("无法找到有效的时间字段:", record);
      return "未知时间";
    }
    return dayjs(timeField).format("YYYY-MM-DD HH:mm:ss");
  }
  // 如果是字符串（直接时间值）
  return dayjs(timeOrRecord).format("YYYY-MM-DD HH:mm:ss");
};

const isNew = (timeOrRecord) => {
  // 如果是对象（通知记录）
  if (typeof timeOrRecord === 'object' && timeOrRecord !== null) {
    const record = timeOrRecord;
    // 按优先级尝试不同的时间字段
    const timeField = record.createTime || record.updateTime || record.time || record.readTime;
    if (!timeField) return false;
    return dayjs().diff(dayjs(timeField), "hour") < 24;
  }
  // 如果是字符串（直接时间值）
  return dayjs().diff(dayjs(timeOrRecord), "hour") < 24;
};

const getNotificationTypeLabel = (type) => {
  const types = {
    pending: "待处理",
    review: "待审核",
    alert: "异常提醒",
    system: "系统通知",
  };
  return types[type] || type;
};

const getNotificationTypeColor = (type) => {
  const colors = {
    pending: "orange",
    review: "blue",
    alert: "red",
    system: "green",
  };
  return colors[type] || "default";
};

const getModuleLabel = (module) => {
  const modules = {
    merchant: "商家管理",
    order: "订单管理",
    content: "内容管理",
    user: "用户管理",
    system: "系统",
  };
  return modules[module] || module;
};

const handleAction = (message) => {
  if (message.actionUrl) {
    router.push(message.actionUrl);
    // 自动标记为已读
    if (!message.isRead) {
      handleMarkRead(message);
    }
  }
};

const handleMarkRead = async (message) => {
  try {
    const success = await notificationStore.markAsRead(message.id);
    if (success) {
      Message.success(`已${message.isRead ? "标记已读" : "标记未读"}`);
    } else {
      Message.error("操作失败");
    }
  } catch (error) {
    Message.error("操作失败");
  }
};

const handleMarkAllRead = () => {
  Modal.confirm({
    title: "确认提示",
    content: "确定要将所有消息标记为已读吗？",
    okText: "确认",
    cancelText: "取消",
    onOk: async () => {
      try {
        const success = await notificationStore.markAllAsRead();
        if (success) {
          Message.success("已全部标记为已读");
        } else {
          Message.error("操作失败");
        }
      } catch (error) {
        Message.error("操作失败");
      }
    },
  });
};

const handleDelete = async (message) => {
  try {
    const success = await notificationStore.deleteNotification(message.id);
    if (success) {
      Message.success("删除成功");
    } else {
      Message.error("删除失败");
    }
  } catch (error) {
    Message.error("删除失败");
  }
};

const handleClearAll = () => {
  Modal.confirm({
    title: "确认提示",
    content: "确定要清空所有消息吗？此操作不可恢复！",
    type: "warning",
    okText: "确认清空",
    cancelText: "取消",
    onOk: async () => {
      try {
        const success = await notificationStore.clearAllNotifications();
        if (success) {
          Message.success("已清空所有消息");
        } else {
          Message.error("清空失败");
        }
      } catch (error) {
        Message.error("清空失败");
      }
    },
  });
};

// 修改获取数据的方法
const fetchNotifications = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      status: filterForm.value.status,
      module: filterForm.value.module !== "all" ? filterForm.value.module : undefined,
      startTime: filterForm.value.timeRange?.[0],
      endTime: filterForm.value.timeRange?.[1],
      type: activeTab.value !== "all" ? activeTab.value : undefined,
    };
    
    const data = await notificationStore.fetchNotifications(params);
    // 更新分页信息
    if (data && typeof data.total === 'number') {
      pagination.value.total = data.total;
    } else {
      // 如果没有明确的total字段，使用数组长度
      pagination.value.total = notificationStore.notifications.length;
    }
    
    // 调试输出
    console.log("获取到的通知列表：", notificationStore.notifications);
  } catch (error) {
    console.error("获取消息列表失败:", error);
    Message.error("获取消息列表失败");
  } finally {
    loading.value = false;
  }
};

const handleFilter = () => {
  pagination.value.current = 1;
  fetchNotifications();
};

const resetFilter = () => {
  filterForm.value = {
    timeRange: [],
    status: "all",
    module: "all",
  };
  handleFilter();
};

const onPageChange = (current) => {
  pagination.value.current = current;
  fetchNotifications();
};

const onPageSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  pagination.value.current = 1;
  fetchNotifications();
};

// 监听标签页变化
watch(activeTab, () => {
  pagination.value.current = 1;
  fetchNotifications();
});

// 生命周期钩子
onMounted(async () => {
  await fetchNotifications();
  // 初始化完成后定期刷新未读数量
  setInterval(() => {
    notificationStore.fetchUnreadCount();
  }, 60000); // 每分钟刷新一次未读数
});
</script>

<style lang="less" scoped>
.notification-page {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      h2 {
        margin: 0;
        color: var(--color-text-1);
      }

      .message-stats {
        display: flex;
        align-items: center;
        font-size: 14px;

        .total-messages {
          color: var(--color-text-2);
        }

        .unread-messages {
          color: var(--color-text-2);

          .number {
            color: rgb(var(--danger-6));
            font-weight: 600;
            font-size: 16px;
            margin: 0 2px;
          }
        }

        :deep(.arco-divider-vertical) {
          height: 14px;
          margin: 0 8px;
          border-left-color: var(--color-neutral-3);
        }
      }
    }

    .header-right {
      :deep(.arco-btn) {
        height: 32px;
        padding: 0 16px;

        .arco-icon {
          font-size: 16px;
        }
      }
    }
  }

  .notification-content {
    background: var(--color-bg-2);
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .filter-card {
      margin-bottom: 16px;

      .filter-section {
        padding: 16px;
        background: var(--color-fill-2);
        border-radius: 4px;
        margin-bottom: 16px;

        :deep(.arco-form-item) {
          margin-bottom: 0;
          margin-right: 16px;
        }
      }

      .tabs-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 16px;
        border-bottom: 1px solid var(--color-border);

        .tabs-container {
          flex: 1;

          :deep(.arco-tabs) {
            .arco-tabs-nav {
              margin-bottom: 0;
            }

            .arco-tabs-tab {
              padding: 8px 16px;
              height: 20px;
              line-height: 16px;

              &.arco-tabs-tab-active {
                font-weight: 500;
              }

              .tab-title {
                position: relative;
                display: inline-flex;
                align-items: center;

                .arco-badge {
                  position: absolute;
                  top: -6px;
                  right: -12px;
                }
              }
            }
          }
        }
      }
    }

    .message-table {
      :deep(.arco-table) {
        border-radius: 8px;
      }

      :deep(.arco-table-tr) {
        &:hover {
          .arco-table-td {
            background-color: var(--color-fill-2);
          }
        }
      }

      :deep(.arco-table-td) {
        transition: background-color 0.2s;
      }
    }

    .title-cell {
      display: flex;
      align-items: center;
      gap: 8px;

      .new-badge {
        padding: 2px 6px;
        background-color: rgb(var(--primary-6));
        color: #fff;
        border-radius: 10px;
        font-size: 12px;
        line-height: 1;
        transform: scale(0.9);
      }
    }

    :deep(.arco-divider-vertical) {
      margin: 0 4px;
      height: 14px;
      border-left-color: var(--color-neutral-3);
    }

    :deep(.arco-btn-text) {
      padding: 0 4px;

      &:hover {
        background: none;
        color: rgb(var(--primary-6));
      }

      &[status="danger"]:hover {
        color: rgb(var(--danger-6));
      }
    }
  }
}
</style>
